package com.example.librarymanagement.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.librarymanagement.dto.periodical.*;
import com.example.librarymanagement.entity.BookAddRecord;
import com.example.librarymanagement.entity.Periodical;
import com.example.librarymanagement.entity.PeriodicalType;
import com.example.librarymanagement.result.ResultCode;
import com.example.librarymanagement.util.CheckEntityUtil;
import com.example.librarymanagement.util.EnumConst;
import com.example.librarymanagement.vo.PeriodicalVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author zjia
 */
@RestController
@Api(tags = "期刊模块")
@RequestMapping("/periodical")
public class PeriodicalController extends BaseController {

    @GetMapping
    @ApiOperation(value = "查询期刊信息列表")
    @PreAuthorize("hasAnyAuthority('periodical:manage:list','periodical:list:view')")
    public IPage<PeriodicalVo> getPeriodicalList(@Validated PeriodicalListDto periodicalListDto) {
        return periodicalService.getPeriodicalsList(periodicalListDto);
    }

    @GetMapping("/info/{id}")
    @ApiOperation(value = "查询期刊信息")
    @PreAuthorize("hasAnyAuthority('periodical:manage:list','periodical:list:view')")
    public PeriodicalType getPeriodicalInfo(@PathVariable Integer id) {
        PeriodicalType periodicalType = periodicalTypeService.getById(id);
        List<Periodical> periodicalList = periodicalService.list(new QueryWrapper<Periodical>().eq("issn", periodicalType.getIssn()));
        periodicalType.setPeriodicalList(periodicalList);
        return periodicalType;
    }

    @GetMapping("/info/issue")
    @ApiOperation(value = "查询期刊信息")
    @PreAuthorize("hasAnyAuthority('periodical:manage:list','periodical:list:view')")
    public Periodical getPeriodicalIssueInfo(String issn, String issue) {
        Periodical periodical = periodicalService.getOne(new QueryWrapper<Periodical>().eq("issn", issn).eq("issue", issue));
        return periodical;
    }

    @PostMapping("/issue")
    @ApiOperation(value = "增加期数")
    @Transactional(rollbackFor = {Exception.class})
    @PreAuthorize("hasAuthority('periodical:manage:save')")
    public void addPeriodicalIssue(@Validated @RequestBody PeriodicalIssueAddDto periodicalIssueAddDto) {
        PeriodicalType periodicalType = CheckEntityUtil.isNullByColumnEq("issn", periodicalIssueAddDto.getIssn(), periodicalTypeService, ResultCode.PERIODICAL_ACCOUNT_NOT_EXIST);
        Periodical periodical = new Periodical();
        periodicalIssueAddDto.convertToEntity(periodical);
        periodical.setCount(periodical.getTotal());
        periodicalService.save(periodical);
        QueryWrapper<Periodical> queryWrapper = new QueryWrapper<>(periodical);
        Periodical one = periodicalService.getOne(queryWrapper);
        BookAddRecord bookAddRecord = new BookAddRecord();
        bookAddRecord.setBookId(one.getId());
        bookAddRecord.setNumber(periodicalIssueAddDto.getTotal());
        bookAddRecord.setBookPeriodical(EnumConst.PERIODICAL.getCode());
        bookAddRecord.setAddTime(new Date());
        bookAddRecordService.save(bookAddRecord);
        if (periodicalIssueAddDto.getUpdTotalIssue()) {
            periodicalType.setTotalIssue(periodical.getIssue());
            periodicalTypeService.updateById(periodicalType);
        }
    }

    @PostMapping
    @Transactional(rollbackFor = {Exception.class})
    @ApiOperation(value = "增加期刊信息")
    @PreAuthorize("hasAuthority('periodical:manage:save')")
    public void addPeriodicals(@Validated @RequestBody PeriodicalAddDto periodicalAddDto) {
        CheckEntityUtil.isNotNullByColumnEq("issn", periodicalAddDto.getIssn(), periodicalTypeService, ResultCode.PERIODICAL_ACCOUNT_EXIST);
        PeriodicalType periodicalType = new PeriodicalType();
        periodicalAddDto.convertToEntity(periodicalType);
        periodicalTypeService.save(periodicalType);
    }

    @PutMapping
    @ApiOperation(value = "修改期刊信息")
    @PreAuthorize("hasAuthority('periodical:manage:update')")
    public void updPeriodical(@Validated @RequestBody PeriodicalUpdDto periodicalUpdDto) {
        PeriodicalType periodicalType = CheckEntityUtil.isNullById(periodicalUpdDto.getId(), periodicalTypeService, ResultCode.PERIODICAL_ACCOUNT_NOT_EXIST);

        CheckEntityUtil.isNullById(periodicalUpdDto.getTypeId(), typeService, ResultCode.BOOK_TYPE_NOT_EXIST);

        periodicalUpdDto.convertToEntity(periodicalType);
        periodicalTypeService.updateById(periodicalType);

    }

    @PutMapping("/issue")
    @ApiOperation(value = "修改期刊信息")
    @PreAuthorize("hasAuthority('periodical:manage:update')")
    public void updPeriodicalByIssn(@Validated @RequestBody PeriodicalIssueUpdDto periodicalIssueUpdDto) {
        Periodical periodical = CheckEntityUtil.isNullById(periodicalIssueUpdDto.getId(), periodicalService, ResultCode.PERIODICAL_ACCOUNT_NOT_EXIST);
        periodicalIssueUpdDto.convertToEntity(periodical);
        periodicalService.updateById(periodical);
    }

    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = {Exception.class})
    @ApiOperation(value = "删除此期刊（所有期数）")
    @PreAuthorize("hasAuthority('periodical:manage:delete')")
    public void delPeriodicalByIssn(@PathVariable Integer id, String issn) {
        periodicalTypeService.removeById(id);
        periodicalService.remove(new QueryWrapper<Periodical>().eq("issn", issn));
    }

    @DeleteMapping
    @Transactional(rollbackFor = {Exception.class})
    @ApiOperation(value = "删除此期刊的指定期数（不删除期刊）")
    @PreAuthorize("hasAuthority('periodical:manage:delete')")
    public void delPeriodicalByIssue(String issn, String issue) {
        periodicalService.remove(new QueryWrapper<Periodical>().eq("issn", issn).eq("issue", issue));
    }
}
